/* 
 -----------------------------------------------------------------------------
                   Cogaen - Component-based Game Engine (v3)
 -----------------------------------------------------------------------------
 This software is developed by the Cogaen Development Team. Please have a 
 look at our project home page for further details: http://www.cogaen.org
    
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 Copyright (c) 2010 Roman Divotkey

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/

package org.cogaen.demo.view;

import java.awt.event.KeyEvent;

import org.cogaen.box2d.EntityMovedEvent;
import org.cogaen.core.Core;
import org.cogaen.demo.entity.CircleEntity;
import org.cogaen.demo.entity.SquareEntity;
import org.cogaen.demo.state.PhysicsDemoState;
import org.cogaen.entity.EntityCreatedEvent;
import org.cogaen.entity.EntityDestroyedEvent;
import org.cogaen.event.Event;
import org.cogaen.event.EventListener;
import org.cogaen.event.EventManager;
import org.cogaen.event.SimpleEvent;
import org.cogaen.input.KeyPressedEvent;
import org.cogaen.java2d.Camera;
import org.cogaen.java2d.ImageHandle;
import org.cogaen.java2d.Overlay;
import org.cogaen.java2d.SceneManager;
import org.cogaen.java2d.SceneNode;
import org.cogaen.java2d.SpriteHandle;
import org.cogaen.logging.LoggingService;
import org.cogaen.math.EaseInOut;
import org.cogaen.resource.ResourceManager;
import org.cogaen.task.AbstractTask;
import org.cogaen.task.TaskManager;

public class PhysicsDemoView implements EventListener {
	
	/** Smooth factor for animation of gravity indicator. */
	private static final double ARROW_EASE_TIME = 0.1;
	
	private static final String LOGGING_SOURCE = "PhysicsDemoView";
	
	private Core core;
	private SceneManager scnMngr;
	private EventManager evtMngr;
	private UpsHud upsHud;
	private Overlay arrow;
	private ArrowAnimator arrorAnimator;
	
	public PhysicsDemoView(Core core) {
		this.core = core;
		this.scnMngr = SceneManager.getInstance( this.core );
		this.evtMngr = EventManager.getInstance( this.core );
		this.upsHud = new UpsHud( this.core );
	}
	
	public void registerResources(String groupName) {
		ResourceManager resMngr = ResourceManager.getInstance(this.core);
		resMngr.addResource( groupName, new ImageHandle("background_img", "memopad_800x600.jpg") );
		resMngr.addResource( groupName, new SpriteHandle("background_spr", "background_img", PhysicsDemoState.WORLD_WIDTH, PhysicsDemoState.WORLD_WIDTH * 0.75) );
		resMngr.addResource( groupName, new ImageHandle("square_img", "box_64x64.png") );
		resMngr.addResource( groupName, new SpriteHandle("square_spr", "square_img", 2.1, 2.1) );				
		resMngr.addResource( groupName, new ImageHandle("circle_img", "circle_64x64.png") );
		resMngr.addResource( groupName, new SpriteHandle("circle_spr", "circle_img", 2.1, 2.1) );				
		resMngr.addResource( groupName, new ImageHandle("arrow_img", "arrow_64x32.png") );
		resMngr.addResource( groupName, new SpriteHandle("arrow_spr", "arrow_img") );
	}
	
	public void engage() {
		// register for relevant events
		this.evtMngr.addListener(this, EntityCreatedEvent.TYPE);
		this.evtMngr.addListener(this, EntityDestroyedEvent.TYPE);
		this.evtMngr.addListener(this, EntityMovedEvent.TYPE);
		this.evtMngr.addListener(this, KeyPressedEvent.TYPE);

		// set up graphical representation
		this.scnMngr.getScreen().hideMouseCursor();
		this.scnMngr.getRootSceneNode().addVisual( scnMngr.createSpriteVisual("background_spr") );
		this.arrow = this.scnMngr.createOverlay();
		this.scnMngr.centerOverlay(this.arrow);
		this.arrow.addVisual( this.scnMngr.createSpriteVisual("arrow_spr") );
		this.arrow.setAngle(Math.PI * 1.5);
		
		Camera cam = scnMngr.createCamera();
		cam.setZoom( scnMngr.getScreen().getWidth() / PhysicsDemoState.WORLD_WIDTH);						
		
		arrorAnimator = new ArrowAnimator(this.core, this.arrow, ARROW_EASE_TIME, -Math.PI / 2.0);
		TaskManager.getInstance(this.core).attachTask(arrorAnimator);
		this.arrorAnimator.setTargetAngle(-Math.PI / 2.0);
		
		// hud
		this.upsHud.engage();
	}
	
	public void disengage() {
		this.upsHud.disengage();
		this.scnMngr.destroyAll();
		this.scnMngr.getScreen().showMouseCursor();		
		this.evtMngr.removeListener(this);
		this.arrorAnimator.kill();
	}

	public double getAspectRatio() {
		double width = this.scnMngr.getScreen().getWidth();
		double height = this.scnMngr.getScreen().getHeight();
		
		return height / width;
	}
	
	@Override
	public void handleEvent(Event event) {
		if (event.getType().equals( EntityMovedEvent.TYPE) ) {
			EntityMovedEvent entityMoved = (EntityMovedEvent) event;
			moveEntity(entityMoved.getName(), entityMoved.getX(), entityMoved.getY(), entityMoved.getAngle());
		} else if (event.getType().equals( EntityCreatedEvent.TYPE) ) {
			EntityCreatedEvent entityCreated = (EntityCreatedEvent) event;
			createRepresentation(entityCreated.getEntityName(), entityCreated.getEntityType());
		} else if (event.getType().equals( EntityDestroyedEvent.TYPE) ) {
			EntityDestroyedEvent entityDestroyed = (EntityDestroyedEvent) event;
			destroyRepresentation(entityDestroyed.getEntityName());
		} else if (event.getType().equals(KeyPressedEvent.TYPE) ) {
			KeyPressedEvent keyPressed = (KeyPressedEvent) event;
			handleKeyEvent( keyPressed.getKeyCode() );
		}
	}
	

	private void handleKeyEvent(int keyCode) {
		switch (keyCode) {
		case KeyEvent.VK_LEFT:
			this.evtMngr.enqueueEvent( new PhysicsDemoState.ChangeGravityEvent(-9.81, 0.0) );
			this.arrorAnimator.setTargetAngle(0.0);
			break;
			
		case KeyEvent.VK_RIGHT:
			this.evtMngr.enqueueEvent( new PhysicsDemoState.ChangeGravityEvent(9.81, 0.0) );
			this.arrorAnimator.setTargetAngle(Math.PI);
			break;
			
		case KeyEvent.VK_UP:
			this.evtMngr.enqueueEvent( new PhysicsDemoState.ChangeGravityEvent(0.0, 9.81) );
			this.arrorAnimator.setTargetAngle(Math.PI / 2.0);
			break;
			
		case KeyEvent.VK_DOWN:
			this.evtMngr.enqueueEvent( new PhysicsDemoState.ChangeGravityEvent(0.0, -9.81) );
			this.arrorAnimator.setTargetAngle(Math.PI * 1.5);
			break;
			
		case KeyEvent.VK_ESCAPE:
			this.evtMngr.enqueueEvent( new SimpleEvent(PhysicsDemoState.END_OF_PHYSICS) );
			break;
			
		case KeyEvent.VK_Q:
			this.scnMngr.setHighQuality( !this.scnMngr.isHighQuality() );
			break;
		}
	}

	private void destroyRepresentation(String name) {
		this.scnMngr.destroySceneNode(name);
	}

	private void moveEntity(String name, double x, double y, double angle) {
		SceneNode node = this.scnMngr.getSceneNode(name);
		node.setPose(x, y, angle);
	}

	private void createRepresentation(String name, String type) {
		if (SquareEntity.TYPE.equals(type)) {
			createSquareRepresentation(name);
		} else if (CircleEntity.TYPE.equals(type)) {
			createCircleRepresentation(name);
		} else {
			LoggingService.getInstance(this.core).logError(LOGGING_SOURCE, "unknown entity type: " + type);
		}
	}
	
	private void createCircleRepresentation(String name) {
		SceneNode node = this.scnMngr.createSceneNode(name);
		node.addVisual( this.scnMngr.createSpriteVisual("circle_spr") );
		this.scnMngr.getRootSceneNode().addChild(node);		
	}
	
	private void createSquareRepresentation(String name) {
		SceneNode node = this.scnMngr.createSceneNode(name);
		node.addVisual( this.scnMngr.createSpriteVisual("square_spr") );
		this.scnMngr.getRootSceneNode().addChild(node);
	}
	
	private static class ArrowAnimator extends AbstractTask {

		private static final String TASK_NAME = "ArrowAnimator";
		
		private EaseInOut easeInOut;
		private Overlay arrow;
		
		public ArrowAnimator(Core core, Overlay arrow, double easeTime, double initialPosition) {
			super(core, TASK_NAME);
			this.easeInOut = new EaseInOut(initialPosition, easeTime);
			this.arrow = arrow;
		}
		
		public void setTargetAngle(double angle) {			
			while (Math.abs(angle - this.easeInOut.getCurrentValue()) > Math.PI) {
				if (angle < this.easeInOut.getCurrentValue()) {
					angle += Math.PI * 2;
				} else {
					angle -= Math.PI * 2;					
				}
			}
			this.easeInOut.setTargetValue(angle);
		}
		
		@Override
		public void update() {
			this.easeInOut.update( getCore().getDeltaTime() );
			this.arrow.setAngle( this.easeInOut.getCurrentValue() );
		}
	}
	
}
